import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication


class SendEmail:
    def __init__(self, mail_host, mail_user, mail_key, mail_send, receivers, Subject="自动化测试报告_纯文本"):
        self.mail_host = mail_host
        self.mail_user = mail_user
        self.mail_key = mail_key
        self.mail_send = mail_send
        self.receivers = receivers
        self.Subject = Subject

    # 只发送正文内容，不包含附件
    def send_email_by_text(self, context):
        message = MIMEText(context, 'plain', 'utf-8')
        message["Subject"] = self.Subject
        message["From"] = self.mail_send
        message["To"] = self.__to_receivers_convert(self.receivers)
        self.__login_and_send(message)

    def send_email_by_att(self, context, attachment_file_path=None):
        message = MIMEMultipart()
        text_body = MIMEText(context, 'html', 'utf-8')
        message.attach(text_body)
        if attachment_file_path:
            att_file = open(attachment_file_path, "rb")
            att = MIMEApplication(att_file.read())
            att_file_path = os.path.abspath(attachment_file_path)
            file_name = os.path.split(att_file_path)[1]  # [文件夹的路径,文件名]
            att.add_header('content-disposition', 'attachment', filename=file_name)
            message.attach(att)
            att_file.close()  # 记得关闭文件
        message["Subject"] = self.Subject
        message["From"] = self.mail_send
        message["To"] = self.__to_receivers_convert(self.receivers)
        self.__login_and_send(message)

    def __login_and_send(self, message):
        try:
            # 修改这里：使用SMTP_SSL而不是SMTP，并使用465端口
            smtp_obj = smtplib.SMTP_SSL(self.mail_host, 465)
            smtp_obj.login(self.mail_user, self.mail_key)
            smtp_obj.sendmail(self.mail_send, self.receivers, message.as_string())
            smtp_obj.quit()
        except Exception as e:
            print(f"邮件发送失败: {str(e)}")
            raise  # 重新抛出异常以保持原有行为

    # ['212703530@qq.com', 'deyunce@163.com']
    def __to_receivers_convert(self, to_receivers):
        if isinstance(to_receivers, list):
            receivers_str = ''
            for receiver in to_receivers:
                receivers_str = receivers_str + receiver + ';'
                # "212703530@qq.com;deyunce@163.com;"
            return receivers_str
        else:
            print(f'{to_receivers}参数的值必须是列表')  # 也可以写入日志


if __name__ == '__main__':
    mail_host = 'smtp.qq.com'
    mail_user = '1693309388@qq.com'
    mail_key = "pazezxcgvutnbecg"
    sender = '1693309388@qq.com'
    receivers = ["to2_loubst6zf@dingtalk.com", "1986009705@qq.com"]

    # Test data matching the image
    test_data = {
        "test_scenario": "批量发消息",
        "team": "测试团队",
        "project": "Mecho",
        "branch": "main",
        "environment": "测试环境",
        "tester": "枫叶",
        "run_on": "客户端",
        "execution_time": "2025-04-08 15:15:40",
        "total": 23,
        "passed": 23,
        "failed": 0,
        "skipped": 0,
        "pass_rate": "100.00%",
        "avg_response_time": "33.64 ms",
        "total_response_time": "0.74 s",
        "total_time": "1.317 s"
    }
    send_email = SendEmail(mail_host, mail_user, mail_key, sender, receivers, "自动化测试完成提醒")
    send_email.send_main(test_data)
